import React, { Component } from 'react';
import { GLOBAL } from '../../../config/global';
import {
  StyleSheet,
  Text,
  View,
  KeyboardAvoidingView,
  Platform,
  Image,
  TouchableOpacity,
  ScrollView,
  PixelRatio,
  TextInput,
} from "react-native";
import { style } from '../../../theme/style';
import { Common } from '../../../component/common/Common.js';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import ToastUtil from '../../../utils/toast';
import HTTP from '../../../utils/http';
import { API, API_GENERATE } from '../../../config/api';
const scale = GLOBAL.SCALE;
const searchIcon = require('../../../imgs/customer/searchLeft.png');


export class EnterpriseClaimPage extends Component {
  static navigationOptions = ({ navigation, navigationOptions }) => {
    return {
      title: '企业认领',
      headerTintColor: '#fff',
      headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack(); }} color='#fff' />,
      headerStyle: style.head.headerStyle,
    }
  }

  constructor(props) {
    super(props);
    const { choice } = props.navigation.state.params;
    this.state = {
      status: 'data',
      companyId: '',
      companyName: '',
      traderList: [],
      choice: choice || {}
    }
    this.requesting = false;
    this.comments = '';
  }

  searchEnterprise = () => {
    let { companyId, companyName, choice } = this.state;
    this.props.navigation.navigate('SeachSupplierPage', {
      choice,
      companyName,
      companyId,
      type: 'ClaimPage',
      code: 'ALL',
      callBack: (data) => {
        this.setState({
          companyName: data.companyName,
          companyId: data.companyId,
          status: 'loading'
        }, async () => {
          const responseData = await HTTP.POST(API_GENERATE(API.GET_CUSTOMER_DETAIL), {
            companyId: data.companyId,
            bizType: 'COMPANY_BASE_INFO'
          });
          if (responseData) {
            let traderList = responseData.staffCompanyList || [];
            this.setState({
              status: 'data',
              traderList: traderList && traderList.length > 0 ? responseData.staffCompanyList : []
            })
          } else {
            this.setState({
              status: 'data'
            })
          }
        })
      }
    })
  }

  submit = async () => {
    if (this.requesting) return;
    if (!this.formVerify()) return;
    this.requesting = true;
    this.setState({
      status: 'loading'
    })
    let res = await HTTP.POST(API_GENERATE(API.ADD_CLAIM_APPLY), {
      companyId: this.state.companyId,
      comments: this.comments
    });
    this.setState({
      status: 'data'
    })
    if (res) {
      this.requesting = false;
      ToastUtil.showSuccess('提交成功').then(() => {
        this.props.navigation.state.params.callBack && this.props.navigation.state.params.callBack({ success: true });
        this.props.navigation.goBack();
      })
    } else {
      this.requesting = false;
    }
  }

  formVerify = () => {
    let { companyId, companyName } = this.state;
    if (!companyId || !companyName) {
      ToastUtil.showWarning('请选择企业');
      return
    }
    if (!this.comments) {
      ToastUtil.showWarning('请输入申请理由');
      return
    }
    return true
  }

  render () {
    let { status, companyId, companyName, traderList, choice } = this.state;
    return (
      <KeyboardAvoidingView style={styles.container} behavior={Platform.OS === 'ios' ? 'padding' : null} keyboardVerticalOffset={20}>
        <ScrollView style={{ paddingLeft: 20 * scale, paddingRight: 20 * scale }} keyboardShouldPersistTaps={'handled'}>
          <TouchableOpacity style={styles.searchWrap} onPress={() => { this.searchEnterprise() }}>
            <Image source={searchIcon} style={styles.searchIcon} />
            <Text style={{ color: '#848A96' }}>{companyName || '请选择企业名称'}</Text>
          </TouchableOpacity>

          {
            (companyId && companyName) ? (<View style={{ marginTop: 36 * scale }}>
              <TouchableOpacity style={{ marginBottom: 14 * scale }} onPress={() => {
                this.props.navigation.navigate('EnterpriseDetailsPage', {
                  companyId,
                  title: companyName,
                  status: 'PASS',
                  menuKey: 'info',
                  choice
                })
              }}>
                <Text style={{ color: style.color.themeColor }}>{companyName}</Text>
              </TouchableOpacity>
              <View style={{ flexDirection: 'row', }}>
                <Text style={{ fontSize: 15 * scale, lineHeight: 22 * scale }}>当前交易员：</Text>
                <View style={{ flexDirection: 'row', flexWrap: 'wrap', width: 240 * scale }}>
                  {
                    traderList.map((item, index) => {
                      return (
                        <Text style={{ lineHeight: 22 * scale }} key={index}>{item.staffName} | {item.organName} {index == traderList.length - 1 ? '' : '，'}</Text>
                      )
                    })
                  }
                </View>
              </View>
            </View>) : null
          }

          <View>
            <Text style={{ fontSize: 15 * scale, marginTop: 36 * scale, marginBottom: 18 * scale }}>申请理由</Text>
            <TextInput
              ref="reasonInput"
              style={styles.reasonArea}
              returnKeyType="done"
              placeholder={"请输入申请理由"}
              placeholderTextColor="#848A96"
              multiline={true}
              blurOnSubmit={true}
              textAlignVertical='top'
              defaultValue={this.comments}
              underlineColorAndroid='transparent'
              onChangeText={(txt) => this.comments = txt}
              maxLength={200}
            />
          </View>

          <View style={styles.submitWrap}>
            <TouchableOpacity style={styles.submitBtn} onPress={() => { this.submit() }}>
              <Text style={styles.submitText}>确认提交</Text>
            </TouchableOpacity>
          </View>
        </ScrollView>

        {
          status != 'data' ? (<View style={styles.statusStyle}><PageStatusIndex status={status} /></View>) : null
        }
      </KeyboardAvoidingView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F0F4FD',
  },
  searchWrap: {
    backgroundColor: '#fff',
    width: 333 * scale,
    height: 36 * scale,
    borderRadius: 6 * scale,
    flexDirection: 'row',
    alignItems: 'center',
    paddingLeft: 12 * scale,
    paddingRight: 12 * scale,
    marginTop: 16 * scale
  },
  searchIcon: {
    width: 18 * scale,
    height: 18 * scale,
    marginRight: 12 * scale
  },
  reasonArea: {
    backgroundColor: '#fff',
    height: 161 * scale,
    width: 333 * scale,
    borderRadius: 6 * scale,
    paddingTop: 15 * scale,
    paddingBottom: 15 * scale,
    paddingLeft: 20 * scale,
    paddingRight: 20 * scale,
  },
  submitWrap: {
    justifyContent: 'center',
    alignItems: 'center',
    width: 333 * scale,
    marginTop: 60 * scale,
    marginBottom: 50 * scale,
  },
  submitBtn: {
    width: 328 * scale,
    height: 42 * scale,
    backgroundColor: style.color.themeColor,
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 6 * scale,
  },
  submitText: {
    color: '#fff',
  },
  statusStyle: {
    flex: 1,
    position: 'absolute',
    height: '100%',
    width: '100%',
    top: 0,
    left: 0,
    flexDirection: 'column',
    justifyContent: 'center',
    alignItems: 'center'
  },
})